package com.prestamomo.vil.ppa.pmvilmedium.pmviluse;

import android.app.Activity;
import android.util.Log;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class PmvilAtyMd {
    private static final String PMVIL_TAG = "PmvilAtyTols";

    private static List<Activity> pmvilActivitys = Collections
            .synchronizedList(new LinkedList<Activity>());

    public static List<Activity> getPmvilActivitys() {
        return pmvilActivitys;
    }


    public static void pushPmvilAty(Activity pmvilAty) {
        pmvilActivitys.add(pmvilAty);
    }


    public static void popPmvilAty(Activity popPmvilAty) {
        pmvilActivitys.remove(popPmvilAty);
    }

    /**
     * get current Activity
     */
    public static Activity currentPmvilAty() {
        if (pmvilActivitys == null || pmvilActivitys.isEmpty()) {
            return null;
        }
        Activity activity = pmvilActivitys.get(pmvilActivitys.size() - 1);
        return activity;
    }

    /**
     * finish Activity
     */
    public static void finishPmvilCurrentAty() {
        if (pmvilActivitys == null || pmvilActivitys.isEmpty()) {
            return;
        }
        Activity activity = pmvilActivitys.get(pmvilActivitys.size() - 1);
        finishPmvilAty(activity);
    }

    public static void finishPmvilAty(Activity pmviFinisAty) {
        if (pmvilActivitys == null || pmvilActivitys.isEmpty()) {
            return;
        }
        if (pmviFinisAty != null) {
            pmvilActivitys.remove(pmviFinisAty);
            pmviFinisAty.finish();
            pmviFinisAty = null;
        }
    }

    public static Activity findPmvilAty(Class<?> pmvilFinCls) {
        Activity targetPmvilAty = null;
        if (pmvilActivitys != null) {
            for (Activity activity : pmvilActivitys) {
                if (activity.getClass().equals(pmvilFinCls)) {
                    targetPmvilAty = activity;
                    break;
                }
            }
        }
        return targetPmvilAty;
    }

    public static void finishPmvilAllAty() {
        if (pmvilActivitys != null) {
            int i = 0;
            while (i < pmvilActivitys.size()) {
                Activity pmvilActivity = pmvilActivitys.get(i);
                if(!pmvilActivity.isFinishing()){
                    pmvilActivity.finish();
                }
                i++;
            }
            pmvilActivitys.clear();
        }

    }

    public static void appPmvilExit() {
        try {
            finishPmvilAllAty();
        } catch (Exception e) {
            Log.e(PMVIL_TAG, "appExit: " + e.getMessage());
        }
    }
}
